/*jslint sloppy: true */
/*global require */
var angular = require('angular');
var probe = require('../global');
require('./open.html');
probe.controller('AddCase', function (Case, $scope) {
	$scope.caseList = Case.list(function (caseList) {
		$scope.tagTable = caseList.reduce(function (table, caseObj) {
			angular.forEach(caseObj.tags, function (tag) {
				table[tag] = false;
			});

			return table;
		}, {});
	});
	var tagsFilterArr = [];
	$scope.tagsFilterFn = function ($case) {
		if (tagsFilterArr.length === 0) {
			return true;
		}
		
		return tagsFilterArr.every(function (tag) {
			return $case.tags.indexOf(tag) !== -1;
		});
	};
	$scope.keyWord = '';
	$scope.isReviewed = '';

	$scope.resetSelect = function () { $scope.selectIndex = -1; };
	$scope.caseSelection = {};
	$scope.selectCase = function (caseId, e) {
		e.stopPropagation();
		if (!e.ctrlKey) { $scope.caseSelection = {}; }
		$scope.caseSelection[caseId] = !$scope.caseSelection[caseId];
	};

	$scope.insertCase = function () {
		var caseList, list = [];
		angular.forEach($scope.caseSelection, function (isSelected, caseId) {
			if (isSelected) { list.push(caseId); }
		});
		caseList = Case.query({
			list: list.join(','),
			mask: 'createtime,updatetime,tags,projectId,reviewed'
		}, function () {
			var a = $scope.schemas.caseList,
				i = $scope.caseCtrl.selected < 0 ? a.length : $scope.caseCtrl.selected;

			a.splice.apply(a, [i, 0].concat(caseList));
			if ($scope.caseCtrl.selected >= 0) {
				$scope.caseCtrl.selected += list.length;
			}
		});
	};

	// init
	$scope.tagTable = {};
	$scope.resetSelect();
	$scope.$watchCollection('tagTable', function () {
		tagsFilterArr.length = 0;
		angular.forEach($scope.tagTable, function (checked, tag) {
			if (checked) { tagsFilterArr.push(tag); }
		});
	});
});
